package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.VisitorApi;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 访客接口实现类
 */
@DubboService
public class VisitorApiImpl implements VisitorApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Visitors visitors) {
        Date today = new Date();
        visitors.setDate(today.getTime());
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        visitors.setVisitDate(df.format(today));

        Query query = new Query(Criteria.where("userId").is(visitors.getUserId())
                .and("visitorUserId").is(visitors.getVisitorUserId())
                .and("visitDate").is(visitors.getVisitDate()));
        if (mongoTemplate.exists(query, Visitors.class)) {
            Update update = new Update();
            update.set("date", visitors.getDate());
            update.set("from", visitors.getFrom());
            mongoTemplate.updateFirst(query, update, Visitors.class);
        } else {
            mongoTemplate.insert(visitors);
        }
    }

    /**
     * @param userId
     * @param lastTime
     * @return
     */
    @Override
    public List<Visitors> findLast4Visitors(Long userId, Long lastTime) {
        Query query = new Query(Criteria.where("userId").is(userId));
        if(null != lastTime)
            query.addCriteria(Criteria.where("date").gt(lastTime));
        query.with(Sort.by(Sort.Direction.DESC, "date")).limit(4);

        return mongoTemplate.find(query, Visitors.class);
    }

    /**
     * 分页查询访客
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<Visitors> findVisitorsByPage(Long userId, Long page, Long pageSize) {
        Query query = new Query(Criteria.where("userId").is(userId));
        long count = mongoTemplate.count(query, Visitors.class);
        long skip = (page - 1) * pageSize;
        List<Visitors> visitors = new ArrayList<>();
        if(count > skip) {
            query.skip(skip).limit(pageSize.intValue());
            visitors = mongoTemplate.find(query, Visitors.class);
        }
        return new PageResult<>(page, pageSize, count, visitors);
    }
}
